# -*- coding: utf8 -*-
__author__ = 'cosven'

import ast
import datetime
import json
import flask

from blog import mongo
from blog import app

from bson.objectid import ObjectId
from flask import request, redirect
from flask.ext.login import login_required

@app.route('/apis/get_cates')
def get_categories():
    """
    method: get
    :return: 返回一个字典，包含种类的id和name
    """
    categories = list(mongo.db.category.find())
    result = []
    for cate in categories:
        result.append({'id': str(cate['_id']), 'name': cate['name']})
    return result

@app.route('/apis/get_blogs')
def get_blogs():
    """
    method: get
    :return: 返回一个列表，包含每篇博客的所有信息[{blog1},{blog2}]
    """
    blogs = list(mongo.db.blog.find())
    return blogs

@app.route('/apis/save', methods=['POST'])
@login_required
def save_draft():
    """
    保存编辑博客时产生的临时草稿
    :return:
    """
    draft = request.get_json()  # get_json()返回一个python dict对象
    _id = ObjectId(draft['draft_id'])
    draft.pop('draft_id')
    try:
        mongo.db.draft.update({'_id': _id}, {"$set": draft})
    except Exception,e:
        mongo.db.draft.insert(draft)
    return flask.jsonify({'flag': True, 'message': u'保存成功'})


@app.route('/apis/publish', methods=['POST'])
@login_required
def publish_blog():
    """
    发布博客
    :return:
    """
    blog = request.get_json()   # 用来获取blog_id和draft_id
    draft_id = ObjectId(blog['draft_id'])
    draft = mongo.db.draft.find_one({'_id': draft_id})
    draft['mod_date'] = datetime.datetime.now()
    # ObjectId 转换为str之后，长度是24位
    if blog['blog_id'] == '' or len(blog['blog_id']) is not 24:
        """
        新建博客
        """
        draft.pop('_id')
        draft['pub_date'] = datetime.datetime.now()
        draft['read_count'] = 0
        draft['love_count'] = 0
        draft['comments_count'] = 0
        draft['comments'] = []
        mongo.db.blog.insert(draft)
        mongo.db.draft.remove({'_id': draft_id})
        return flask.jsonify({'flag': True, 'message': u'新建博客成功'})
    else:
        """
        修改博客
        """
        _id = ObjectId(blog['blog_id'])
        draft.pop('_id')
        mongo.db.blog.update({'_id': _id}, {"$set": draft})
        mongo.db.draft.remove({'_id': draft_id})
        return flask.jsonify({'flag': True, 'message': u'修改博客成功'})


@app.route('/apis/delete/blog/', methods=['POST'])
@login_required
def delete_blog():
    data = request.get_json()
    _id = data['_id']
    try:
        _id = ObjectId(_id)
    except Exception, e:
        return flask.jsonify({'flag': False, 'message': u'id不符合规范'})
    blog = mongo.db.blog.find_one({'_id': _id})
    if blog is not None:
        mongo.db.blog.remove({'_id': _id})
        return flask.jsonify({'flag': True, 'message': u'删除博客成功'})
    else:
        return flask.jsonify({'flag': False, 'message': u'不存在相应博客'})

@app.route('/apis/delete/draft/', methods=['POST'])
@login_required
def delete_draft():
    data = request.get_json()
    _id = data['_id']
    try:
        _id = ObjectId(_id)
    except Exception, e:
        return flask.jsonify({'flag': False, 'message': u'id不符合规范'})
    draft = mongo.db.draft.find_one({'_id': _id})
    if draft is not None:
        mongo.db.draft.remove({'_id': _id})
        return flask.jsonify({'flag': True, 'message': u'删除草稿成功'})
    else:
        return flask.jsonify({'flag': False, 'message': u'不存在相应草稿'})
